package com.test.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

public class ZookeeperClient {


    private static final String ZOOKEEPER_ADDRESS = "localhost:2181"; // ZooKeeper 地址
    private static final int SESSION_TIMEOUT = 3000; // 会话超时时间

    public static void main(String[] args) {
        ZooKeeper zooKeeper = null;

        try {
            // 连接到 ZooKeeper 服务端
            zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, event -> {
                // 处理事件（可以为空）
            });

            // 创建一个节点
            String path = "/my_node22"; // 节点路径
            String data = "Hello ZooKeeper"; // 节点数据

            // 创建节点，如果节点已存在则会抛出异常
            String createdPath = zooKeeper.create(path, data.getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.PERSISTENT);
            System.out.println("Node created: " + createdPath);

        } catch (IOException e) {
            System.err.println("Failed to connect to ZooKeeper: " + e.getMessage());
        } catch (KeeperException e) {
            System.err.println("ZooKeeper error: " + e.getMessage());
        } catch (InterruptedException e) {
            System.err.println("Operation interrupted: " + e.getMessage());
        } finally {
            // 关闭连接
            if (zooKeeper != null) {
                try {
                    zooKeeper.close();
                } catch (InterruptedException e) {
                    System.err.println("Failed to close ZooKeeper: " + e.getMessage());
                }
            }
        }
    }


}
